﻿using MslDiary.BLL;
using MslDiary.Framework;
using MslDiary.Framework.IO;
using MslDiary.Model;
using MslDiary.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;

// 版权所有：2014  All Rights Reserved.
// 文 件 名：NoteListViewModel.cs
// 功能描述：
// 创建标识：m.sh.lin0328@163.com 2014/12/14 15:39:14
// 修改描述：
//----------------------------------------------------------------*/
namespace MslDiary.ViewModel
{
    public class NoteListViewModel : MslDiary.Framework.ViewModelBase
    {
        private A_NoteBLL noteBLL = new A_NoteBLL();
        private A_ItemBLL itemBLL = new A_ItemBLL();
        private A_Item itemMod = null;

        /// <summary>
        /// 构造
        /// </summary>
        public NoteListViewModel()
        {
            if (!IsInDesignMode)
            {
                this.PageInfoModel = new PageInfo();
                this.PageInfoModel.PageSize = 17;
            }
            this.ButtonAcceptText = "添加";
            this.WindowLoadCommand = new CommandBase((Object parameter) =>
            {
                if (this.NoteList == null || this.NoteList.Count == 0)
                    Load();
            });
            this.SaveCommand = new CommandBase((Object parameter) => Save());
            this.DeleteCommand = new CommandBase((Object parameter) => Delete());
            this.SelectionTypeIdChangedCommand = new CommandBase((Object mod) =>
            {
                if (mod == null) return;
                this.TxtTtile = String.Empty;
                this.itemMod = (A_Item)mod;
                string str = GetWhere();
                if (itemMod.Id != 0)
                    str += " AND TypeId= " + itemMod.Id;
                Bind(str);
            });
            this.PageChangingCommand = new CommandBase((Object parameter) => BindList());
            ResetCommand = new CommandBase((Object parameter) =>
            {
                this.NoteModel = new A_Note();
                this.NoteModel.TypeId = 3;
                this.ButtonAcceptText = "添加";
            });
            this.SearchNoteCommand = new CommandBase((Object parameter) =>
            {
                if (parameter == null || parameter.ToString().Length == 0)
                {
                    MslDiary.Utils.Helper.Instance.Alert(MslDiary.Framework.ShowMessage.SEARCH_MSG02);
                    return;
                }
                this.TxtTtile = parameter.ToString();
                MslDiary.Utils.Helper.Instance.Loading(() =>
                {
                    MslDiary.Framework.Gloable.PageIndex = 1;
                    BindList();
                }, "正在查询...");
            });
            this.SelectionNoteChangedCommand = new CommandBase((Object mod) =>
            {
                if (mod == null) return;
                if (mod.ToString().StartsWith("{New")) return;

                A_Note m = (A_Note)mod;
                if (m == null || m.Id == 0) return;
                this.NoteModel = noteBLL.GetEntity(" Id=" + m.Id);
                this.ButtonAcceptText = "更新";
            });
        }

        #region 命令

        public ICommand _noteSelectedChangedCommand;
        public ICommand ResetCommand { get; set; }
        /// <summary>
        /// 加载
        /// </summary>
        public ICommand WindowLoadCommand { set; get; }
        /// <summary>
        /// 关闭
        /// </summary>
        public ICommand CloseCommand { set; get; }
        /// <summary>
        /// 关闭
        /// </summary>
        public ICommand SaveCommand { set; get; }
        /// <summary>
        /// 删除
        /// </summary>
        public ICommand DeleteCommand { set; get; }
        /// <summary>
        /// 列表选择
        /// </summary>
        public ICommand NoteSelectedChangedCommand
        {
            get
            {
                if (_noteSelectedChangedCommand == null)
                {
                    _noteSelectedChangedCommand = new CommandBase((Object n) =>
                    {
                        this.NoteModel = (A_Note)n;
                        this.ButtonAcceptText = "修改";
                    });
                }
                return _noteSelectedChangedCommand;
            }
        }
        /// <summary>
        /// 分页事件
        /// </summary>
        public ICommand PageChangingCommand { set; get; }
        /// <summary>
        /// 查询事件
        /// </summary>
        public ICommand SearchNoteCommand { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public ICommand SelectionNoteChangedCommand { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public ICommand SelectionTypeIdChangedCommand { set; get; }
        #endregion

        #region 属性
        private ObservableCollection<A_Note> _notelist;
        private A_Note _noteModel;
        private PageInfo _pageInfoModel;
        /// <summary>
        /// 查询
        /// </summary>
        public A_Note NoteModel
        {
            get { return _noteModel; }
            set
            {
                //base.SetProperty<A_Note>(ref this._noteModel, value);
                if (this._noteModel == value)
                    return;
                this._noteModel = value;
                this.RaisePropertyChanged("NoteModel");
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        public string TxtTtile { get; set; }
        public PageInfo PageInfoModel
        {
            get { return _pageInfoModel; }
            set
            {
                //base.SetProperty<PageInfo>(ref this._pageInfoModel, value);
                if (this._pageInfoModel == value)
                    return;
                this._pageInfoModel = value;
                this.RaisePropertyChanged("PageInfoModel");
            }
        }
        /// <summary>
        /// 笔记列表
        /// </summary>
        public ObservableCollection<A_Note> NoteList
        {
            get { return _notelist; }
            set
            {
                //base.SetProperty<ObservableCollection<A_Note>>(ref this._notelist, value);
                if (this._notelist == value)
                    return;
                this._notelist = value;
                this.RaisePropertyChanged("NoteList");
            }
        }
        private List<A_Item> _noteTypeList;
        /// <summary>
        /// 笔记类型
        /// </summary>
        public List<A_Item> NoteTypeList
        {
            get { return _noteTypeList; }
            set
            {
                //base.SetProperty<List<A_Item>>(ref this._noteTypeList, value);
                if (this._noteTypeList == value)
                    return;
                this._noteTypeList = value;
                this.RaisePropertyChanged("NoteTypeList");
            }
        }

        private string btnAddText = "添加";
        /// <summary>
        /// 添加按钮文字
        /// </summary>
        public string ButtonAcceptText
        {
            get { return btnAddText; }
            set
            {
                //base.SetProperty<string>(ref this.btnAddText, value);
                if (this.btnAddText == value)
                    return;
                this.btnAddText = value;
                this.RaisePropertyChanged("ButtonAcceptText");
            }
        }
        #endregion

        #region 方法

        /// <summary>
        /// 加载
        /// </summary>
        private void Load()
        {
            this.NoteModel = new A_Note();
            this.NoteTypeList = itemBLL.GetList(" FatherId=1 ", " Id,Name,CreateDate ", "Id");
            //this.NoteTypeList.Insert(0, new A_Item() { Name = "全部" });
            BindList();
        }
        private void Bind(string whereStr)
        {
            int totalCount = 0;
            if (String.IsNullOrEmpty(whereStr))
                whereStr = "1=1";
            this.NoteList = new ObservableCollection<A_Note>(
                noteBLL.GetPageList(SearchType.All, whereStr, PageInfoModel.PageSize, MslDiary.Framework.Gloable.PageIndex, " ModifyDate DESC", out totalCount)
            );
            PageInfoModel.TotalCount = totalCount;
        }
        private string GetWhere()
        {
            string whereStr = " 1=1 ";
            if (this.TxtTtile != null && this.TxtTtile.Length > 0)
                whereStr += " AND Title LIKE '%" + this.TxtTtile + "%' ";

            return whereStr;
        }
        private void BindList()
        {
            string str = GetWhere();
            Bind(str);
        }
        private void Delete()
        {
            if (this.NoteModel == null || this.NoteModel.Id == 0)
            {
                MslDiary.Utils.Helper.Instance.AlertWarning(MslDiary.Framework.ShowMessage.DEL_MSG01);
                return;
            }
            MslDiary.Utils.Helper.Instance.AlertConfirm("警告", MslDiary.Framework.ShowMessage.DEL_MSG02, () =>
            {
                if (noteBLL.Delete(" Id=" + NoteModel.Id) > 0)
                {
                    MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                    this.NoteList.Remove(this.NoteModel);
                    return;
                }
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.SYS_MSG01);
            });
        }
        private void Save()
        {
            if (NoteModel == null || String.IsNullOrEmpty(NoteModel.Title) || String.IsNullOrEmpty(NoteModel.Content))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("标题或内容不能为空！");
                return;
            }
            try
            {
                this.NoteModel.TypeName = null;
                this.NoteModel.Summary = this.NoteModel.Content.Length > 1500 ? this.NoteModel.Content.Substring(0, 1500) : this.NoteModel.Content;
                if (this.NoteModel.Id == 0)//新增
                {
                    this.NoteModel.CreateDate = DateTime.Now;
                    if (noteBLL.Add(this.NoteModel) > 0)
                    {
                        MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                        //更新集合
                        this.NoteModel.TypeName = itemBLL.GetItemNameById(this.NoteModel.TypeId);
                        this.NoteList.Insert(0, this.NoteModel);
                    }
                    else
                        MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                }
                else
                {
                    this.NoteModel.ModifyDate = DateTime.Now;
                    if (noteBLL.Update(this.NoteModel, " Id=" + NoteModel.Id) > 0)
                    {
                        MslDiary.Utils.Helper.Instance.AlertSuccess(MslDiary.Framework.ShowMessage.OPERATE_MSG01);
                        //更新集合
                        List<A_Note> list = new List<A_Note>(this.NoteList);
                        int n = list.FindIndex(m =>
                        {
                            return m.Id == this.NoteModel.Id;
                        });
                        list = null;
                        this.NoteList.RemoveAt(n);
                        this.NoteModel.TypeName = itemBLL.GetItemNameById(this.NoteModel.TypeId);
                        this.NoteList.Insert(n, this.NoteModel);
                    }
                    else
                        MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.OPERATE_MSG02);
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog("NoteListViewModel Save", ex.ToString());
                MslDiary.Utils.Helper.Instance.AlertError(MslDiary.Framework.ShowMessage.SYS_MSG01);
            }
        }
        #endregion
    }
}